#!/bin/sh
#
# mkpkg - Builds a pkgadd-installable package from a listing of the contents in
# a staging directory.
#
# This is a modified version of a script written by mark@metalab.unc.edu .
# The original is at http://metalab.unc.edu/pub/packages/solaris/sparc/html/creating.solaris.packages.html .

if [ "$1" != "" ] ; then
  pkg=$1
else
  echo "Usage: " `basename $0` " <package name> [output file]"
  exit 1
fi

if [ "$2" != "" ] ; then
  pkgfile=$2
else
  pkgfile=$pkg
fi

if [ "$3" != "" ] ; then
  prefix=$3
else
  prefix=/usr/local
fi

if [ "$4" != "" ] ; then
  srcdir=$4
else
  srcdir=`basename $0`/../..
fi

# Initialize our variables
prepdir=`dirname $0`
prototype="$prepdir/Prototype"
stagedir=$srcdir/${pkg}.inst

# Create the Prototype file
cat > $prototype <<Fin
i pkginfo
i checkinstall
Fin
if [ ! -d $stagedir ] ; then
  echo "Whoops! Staging directory $stagedir doesn't exist.  Bailing."
  exit 1
fi

find $stagedir/$prefix/* -print | \
  pkgproto $stagedir/$prefix=$prefix | \
  # Mimic file permissions under /usr
  awk ' \
    /bin/ { print $1, $2, $3, $4, "root bin"; next }; \
    /lib/ { print $1, $2, $3, $4, "root bin"; next }; \
    /man/ { print $1, $2, $3, $4, "root bin"; next }; \
    { print $1, $2, $3, $4, "root sys" } \
  ' \
  >> $prototype

# Make the package installation directory
pkgmk -o -r / -d /$srcdir -f $prototype
echo "Setting file permissions in $stagedir tree to 644."
find $stagedir -type f -print | xargs chmod a+r
find $stagedir -type f -print | xargs chmod u+w
echo "Setting directory permissions in $stagedir tree to 755."
find $stagedir -type d -print | xargs chmod 755
if [ -f $stagedir/install/preinstall ]; then
    chmod 755 $stagedir/install/preinstall
fi
if [ -f $stagedir/install/postinstall ]; then
    chmod 755 $stagedir/install/postinstall
fi
if [ -f $stagedir/install/preremove ]; then
    chmod 755 $stagedir/install/preremove
fi
if [ -f $stagedir/install/postremove ]; then
    chmod 755 $stagedir/install/postremove
fi
if [ -f $stagedir/install/request ]; then
    chmod 755 $stagedir/install/request
fi
if [ -f $stagedir/install/checkinstall ]; then
    chmod 755 $stagedir/install/checkinstall
fi

# Spool the install directory into its own self-contained file.
pkgtrans -s $srcdir $pkgfile $pkg

# echo "Compressing package file"
# gzip -9 $srcdir/$pkgfile
